package dsf.eshop.user.service;

import dsf.eshop.commons.base.BaseResult;
import dsf.eshop.user.dao.UserMapper;
import dsf.eshop.user.entity.User;
import dsf.eshop.user.entity.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
    public BaseResult register(User user) {

        if(user.getEmail() == null || user.getPassword() == null) {

            return new BaseResult(1, "邮箱或密码不能为空");
        }

        UserExample userExample = new UserExample();
        userExample.createCriteria().andEmailEqualTo(user.getEmail());
        if(1 == userMapper.countByExample(userExample)) {
            return new BaseResult(1, "邮箱已注册");
        }

        if(1 == userMapper.insertSelective(user)) {

            return new BaseResult(0, "注册成功");
        } else {
            return new BaseResult(1, "请稍后重试");
        }

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public List<User> list(int page, int size) {

        UserExample userExample = new UserExample();

        return userMapper.selectByExampleAndPage(null, size, size * (page - 1));
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public User datail(int id) {

        return userMapper.selectByPrimaryKey(id);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public BaseResult add(User user) {

        user.setUserId(null);
        if(user.getEmail() == null || user.getEmail().equals("")) {
            return new BaseResult(1, "邮箱不能为空");
        }
        int result = userMapper.insertSelective(user);
        if(1 == result) {
            return new BaseResult(0, "添加成功");
        } else {
            return new BaseResult(1, "添加失败");
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public BaseResult update(User user) {

        int result = userMapper.updateByPrimaryKeySelective(user);
        if(1 == result) {
            return new BaseResult(0, "修改成功");
        } else {
            return new BaseResult(1, "未修改");
        }
    }

}
